package com.english_test_sys.controller;


import com.english_test_sys.pojo.User;
import com.english_test_sys.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Map;


@Controller
public class UserController {

    @Autowired
    private UserService userService;

    // 登录页面
    @GetMapping("/login")
    public String loginPage(Model model) {
        return "login";
    }

    // 注册页面
    @GetMapping("/register")
    public String registerPage(Model model) {
        return "register";
    }

    // 处理登录请求
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        Model model) {

        User user = userService.login(username, password);
        if (user != null) {
            session.setAttribute("user", user);

            if ("admin".equalsIgnoreCase(user.getUserType())) {
                return "Admin";
            } else {
                return "/English_test_home";

            }
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }
    }

    // 处理注册请求
    @PostMapping("/register")
    public String register(@RequestParam String username,
                           @RequestParam String password,
                           @RequestParam String email,
                           Model model) {

        if (userService.findByUsername(username) != null) {
            model.addAttribute("error", "用户名已存在");
            return "register";
        }

        User newUser = new User(username, password, email, "student", 0);
        userService.register(newUser);

        model.addAttribute("success", "注册成功，请登录");
        return "login";
    }

    @GetMapping("/practise")
    public String practise() {
        return "practise";
    }

    @GetMapping("/wrong_questions")
    public String wrong_questions() {
        return "wrong_questions";
    }

    // 注销
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/html/login.html";
    }
    @PostMapping("/api/updateScore")
    public ResponseEntity<?> updateScoreByUsername(
            @RequestBody Map<String, Object> request,
            HttpSession session) {
        try {
            User sessionUser = (User) session.getAttribute("user");
            String username = sessionUser != null ? sessionUser.getUsername() :
                    (String) request.get("username");

            Integer scoreToAdd;
            try {
                scoreToAdd = Integer.parseInt(request.get("score").toString());
            } catch (NumberFormatException e) {
                return ResponseEntity.badRequest().body(
                        Collections.singletonMap("error", "Score must be a number"));
            }

            if (username == null || username.isEmpty()) {
                return ResponseEntity.badRequest().body(
                        Collections.singletonMap("error", "Username is required"));
            }

            User user = userService.findByUsername(username);
            if (user == null) {
                return ResponseEntity.badRequest().body(
                        Collections.singletonMap("error", "User not found"));
            }

            Integer currentScore = user.getScore() != null ? user.getScore() : 0;
            Integer newScore = currentScore + scoreToAdd;

            User updatedUser = userService.updateScoreByUsername(username, newScore);

            return ResponseEntity.ok().body(updatedUser);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(
                    Collections.singletonMap("error", e.getMessage()));
        }
    }
}